from threading import Thread
from flask_mail import Message
from flask import current_app, render_template
from app.extensions import mail

def async_send_mail(msg,app):
    # 邮件发送需要诚信上下文，否则发送不了
    # 由于是新的线程，没有上下文，需要手动创建
    with app.app_context():
        mail.send(msg)
    pass

# 使用进程发送邮件
def send_mail(to,subject,template,**kwargs):
    # 获取原生的app对象
    app = current_app._get_current_object()
    sender = current_app.config['MAIL_USERNAME']
    msg = Message(subject=subject,recipients=[to],sender=sender)
    msg.html = render_template(template+'.html',**kwargs)
    # msg.body = render_template(template+'.txt')
    thr = Thread(target=async_send_mail,args=[msg,app])
    thr.start()
    return thr